package com.example.zfb_website.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @description: 支付宝网站支付工具类
 * @author: qiu bo yang
 * @create: 2020-08-14 09:25
 */
@Slf4j
public class AliPayUtils {
    //支付宝网关
    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    //支付宝appId
    private static final String APP_ID = "";
    //商户私钥
    private static final String MERCHANT_PRIVATE_KEY = "";
    //编码格式
    private static final String CHARSET = "UTF-8";
    //支付宝公钥
    private static final String ALIPAY_PUBLIC_KEY = "";
    //验证类型
    private static final String SIGN_TYPE = "RSA2";
    //传参格式
    private static final String FORMAT = "json";
    //产品码
    private static final String PRODUCT_CODE = "FAST_INSTANT_TRADE_PAY";

    /**
     * 发起支付宝网站支付
     *
     * @param outTradeNo 订单号
     * @param money      金额
     * @param subject    产品描述
     * @return
     */
    public static String sendAliPayOrder(String outTradeNo, String money, String subject) {
        try {
            AliPayVo alipayVo = new AliPayVo();
            alipayVo.setOut_trade_no(outTradeNo);
            alipayVo.setTotal_amount(money);
            alipayVo.setSubject(subject);
            alipayVo.setProduct_code(PRODUCT_CODE);
            String json = JSONArray.toJSON(alipayVo).toString();
            log.info("请求参数：{}", json);
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, MERCHANT_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
            // 设置请求参数
            AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
            //设置支付成功返回页面
            alipayTradePagePayRequest.setReturnUrl("https://www.baidu.com/");
            //设置回调地址
            alipayTradePagePayRequest.setNotifyUrl("http://qiuboyang.vaiwan.com/zfb/notify");
            alipayTradePagePayRequest.setBizContent(json);
            String result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
            log.info("支付宝发起支付成功: {}", result);
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 支付回调验证签名
     *
     * @param map
     * @return
     */
    public static boolean verifySign(Map<String, String> map) {
        boolean signVerified = false;
        try {
            // 调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(map, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return signVerified;
    }

    /**
     * 支付宝回调请求参数转化为map
     *
     * @param request
     * @return
     */
    public static Map<String, String> getPayBackFormat(HttpServletRequest request) {
        Map<String, String> tempParams = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator it = requestParams.keySet().iterator(); it.hasNext(); ) {
            String name = (String) it.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ?
                        valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            tempParams.put(name, valueStr);
        }
        return tempParams;
    }

   /* public static void main(String[] args) {
        String outTradeNo = System.currentTimeMillis()+"";
        String money = "100";
        String subject = "水杯";
        sendAliPayOrder(outTradeNo,money,subject);
    }*/
}
